﻿using System;
using Kugar.Core.ExtMethod;

namespace Kugar.Tool.Web.RequestFieldValidation.Converters
{
    internal class NumericConverter : IRequestValueConverter
    {
        public object ConvertTo<T>(string inputValue, string format, object defaultValue)
        {
            try
            {
                //var type = Nullable.GetUnderlyingType(typeof(T));
                //if (type != null)
                //{
                //    if (string.IsNullOrWhiteSpace(inputValue))
                //    {
                //        return null;
                //    }

                //    return inputValue.ConvertToPrimitive<T>((T)defaultValue);

                    
                //}

                return inputValue.ConvertToPrimitive<T>((T)defaultValue);

                return (T)Convert.ChangeType(inputValue, typeof(T));
            }
            catch (Exception e)
            {
                return (T)defaultValue;
            }

        }

        public bool CanConvert(Type valueType)
        {
            var nullableType = Nullable.GetUnderlyingType(valueType);

            return valueType.IsNumericType() || valueType.IsPrimitive || nullableType?.IsPrimitive == true || nullableType?.IsNumericType() == true;
        }
    }
}